var express = require('express');
var router = express.Router();
const { Article } = require('../../models');
const { Op } = require('sequelize');
const { failureResponse, successResponse } = require('../../utils/responses');
const { BadRequestError } = require('../../utils/errors');


router.get('/', async function(req, res, next) {
  try {
    const { title, deleted } = req.query;
    const currentPage = parseInt(req.query.currentPage) || 1; // 当前页码，默认为 1
    const pageSize = parseInt(req.query.pageSize) || 10; // 每页数量，默认为 10
    const offset = (currentPage - 1) * pageSize;
    const condition = {
      order: [['id', 'DESC']], // 按照 id 降序排列
      limit: pageSize,
      offset: offset,
      where: {}
    }
    // 查询被软删除的数据
    if (deleted) {
      condition.paranoid = false;
      condition.where.deletedAt = {
        [Op.not]: null
      }
    }

    if (title) {
      condition.where.title = {
        [Op.like]: `%${title}%` // 模糊查询标题
      }
    }
    // 查询所有文章
    const { rows, count } = await Article.findAndCountAll(condition)
    successResponse(res, '查询文章列表成功', {
      articles: rows,
      pagination: {
        pageSize,
        currentPage,
        total: count
      }
    })
  } catch (error) {
    failureResponse(res, error);
  }
});

router.get('/:id', async function(req, res, next) {
  try {
    const { id } = req.params;
    // 查询主键 id 的文章
    const article = await Article.findByPk(id);
    if (!article) {
      throw new BadRequestError('文章没有找到');
    }
    successResponse(res, '查询文章详情成功', { article });
  } catch (error) {
    failureResponse(res, error);
  }
})

router.post('/', async function(req, res, next) {
  try {
    const article = await Article.create(filterBody(req.body));
    successResponse(res, '创建文章成功', { article }, 201);
  } catch (error) {
    failureResponse(res, error);
  }
})

// delete 不适合删除多个数据, 改为 post 软删除多个文章到回收站
router.post('/delete', async function(req, res, next) {
  try {
    const { ids } = req.body;
    await Article.destroy({
      where: {
        id: ids
      }
    })
    successResponse(res, '删除文章成功');
  } catch (error) {
    failureResponse(res, error);
  }
})

// 从回收站恢复文章
router.post('/restore', async function(req, res, next) {
  try {
    const { ids } = req.body;
    await Article.restore({
      where: {
        id: ids
      }
    })
    successResponse(res, '恢复文章成功');
  } catch (error) {
    failureResponse(res, error);
  }
})

// 彻底删除
router.post('/force_delete', async function(req, res, next) {
  try {
    const { ids } = req.body;
    await Article.destroy({
      where: {
        id: ids,
      },
      force: true
    })
    successResponse(res, '彻底删除文章成功');
  } catch (error) {
    failureResponse(res, error);
  }
})


// router.delete('/:id', async function(req, res, next) {
//   const { id } = req.params;
//   try {
//     const article = await Article.findByPk(id);
//     if (!article) {
//       throw new BadRequestError('文章没有找到');
//     }
//     await article.destroy();
//     successResponse(res, '删除文章成功');
//   } catch (error) {
//     failureResponse(res, error);
//   }
// })

router.put('/:id', async function(req, res, next) {
  const { id } = req.params;
  try {
    const article = await Article.findByPk(id);
    if (!article) {
      throw new BadRequestError('文章没有找到');
    }
    await article.update(filterBody(req.body));
    successResponse(res, '更新文章成功', { article });
  } catch (error) {
    failureResponse(res, error);
  }
})

function filterBody(body) {
  const { title, content } = body;
  return {
    title: title ? title.trim() : '',
    content: content ? content.trim() : ''
  };
}

module.exports = router;
